using System;
using System.Collections.Generic;
using System.Xml;
using XmlObjects.XmlDocumentMarkup;

namespace XmlObjects
{
	public class DocumentElement
	{
		public XmlDocument CreateXmlDocument()
		{
			XmlDocument document = new XmlDocument();
			if (!AttributePropertyReader.IsXmlElement(GetType()))
				throw new Exception(string.Format("Type '{0}' has no XmlElement attribute.", GetType()));

			XmlElementAttribute attribute =
				(XmlElementAttribute) GetType().GetCustomAttributes(typeof (XmlElementAttribute), true)[0];
			AppendTo(attribute.Name, document, document);
			return document;
		}

		public void ReadFrom(XmlNode node)
		{
			if (null == node)
				throw new ArgumentNullException("node");

			IList<IXmlDocumentPropertyReader> propertyReaders = DocumentPropertyReader.GetPropertyReaders(this);
			foreach (IXmlDocumentPropertyReader propertyReader in propertyReaders)
			{
				propertyReader.ReadXml(node, this);
			}
		}

		public void AppendTo(string name, XmlNode node, XmlDocument owner)
		{
			XmlNode myNode = node.SelectSingleNode(name);
			if (myNode == null)
			{
				myNode = owner.CreateElement(name);
				node.AppendChild(myNode);
			}

			IList<IXmlDocumentPropertyReader> propertyReaders = DocumentPropertyReader.GetPropertyReaders(this);
			foreach (IXmlDocumentPropertyReader propertyReader in propertyReaders)
			{
				propertyReader.WriteXml(myNode, this, owner);
			}
			node.AppendChild(myNode);
		}
	}
}